<template>
    <el-dialog :title="title" :visible="visible" width="60%" :show-close="true" @close="close" :close-on-click-modal="false">
        <el-form ref="form" label-width="80px" :model="formLabelAlign" :rules="rules">
            <el-form-item label="名称" prop='permissionName'>
                <el-input v-model="formLabelAlign.permissionName" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="permissionDesc">
                <el-input v-model="formLabelAlign.permissionDesc" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item label="请求路径" prop='uri'>
                <el-input v-model="formLabelAlign.uri" placeholder="请输入后端接口"></el-input>
            </el-form-item>
            <el-form-item v-if="handleType == 2" label="权限标识" prop="code">
                <el-select v-if="handleType == 2" v-model="formLabelAlign.code" placeholder="请选择按钮类型">
                    <el-option v-for="item in authKeys" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="路由" prop="path" v-if="!disable">
                <el-select v-model="formLabelAlign.path" placeholder="请选择路由">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.path">
                    </el-option>
                </el-select>
                <el-tag type="danger" style="margin-left: 8px;">如果为空表示没有可添加路由</el-tag>
            </el-form-item>
            <el-form-item label="路由名称" prop='title' v-if="!disable">
                <el-input v-model="formLabelAlign.title" placeholder="请输入路由名称"></el-input>
            </el-form-item>
            <el-form-item label="菜单图标" prop="icon" v-if="!disable">
                <el-popover placement="top-start" width="450" title="选择icon" trigger="click">
                    <div class="icon-selector">
                        <div class="icon-list">
                            <el-tooltip v-for="icon in filteredIcons" :key="icon" :content="icon" placement="top">
                                <div class="icon-item" :class="{ 'active': formLabelAlign.icon === icon }"
                                    @click="selectIcon(icon)">
                                    <i :class="icon"></i>
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                    <el-input slot="reference" v-model="formLabelAlign.icon" placeholder="请选择图标" readonly>
                        <template #prefix>
                            <i :class="formLabelAlign.icon" v-if="formLabelAlign.icon"></i>
                        </template>
                    </el-input>
                </el-popover>
            </el-form-item>
            <el-form-item label="是否显示" prop="visible">
                <el-switch v-model="formLabelAlign.visible" active-color="#409EFF" inactive-color="#DCDFE6"
                    active-text="显示" inactive-text="隐藏" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="formLabelAlign.sort" :min="1" :max="10" />
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
// Element UI 官方图标列表
const elementIcons = [
    'el-icon-user',
    'el-icon-menu',
    'el-icon-setting',
    'el-icon-document',
    'el-icon-s-goods',
    'el-icon-s-shop',
    'el-icon-printer',
    'el-icon-office-building',
    'el-icon-shopping-bag-1',
    'el-icon-house',
    'el-icon-chat-dot-round',
    'el-icon-truck',
    'el-icon-s-order',
    'el-icon-s-operation',
    'el-icon-money',
    'el-icon-s-custom',
    'el-icon-bank-card',
    'el-icon-s-marketing',
    'el-icon-s-platform'
];

export default {
    props: ['visible', 'isEdit', 'disable', 'loading', 'title', 'handleType', 'type'],
    data() {
        const routes = this.$router.options.routes.filter(i => i.path !== '/');
        const authRoute = JSON.parse(localStorage.getItem('route'));
        let existRoute = [];
        authRoute.forEach(i => {
            existRoute.push(i.path);
            if (i.children) {
                i.children.forEach(j => {
                    existRoute.push(j.path)
                })
            }
        })
        // console.log(1, '权限路由', existRoute);

        let menuPath = [], pagePath = {};
        routes.forEach(i => {
            if (i.children) {
                pagePath[i.path] = [];
                i.children.forEach(ele => {
                    // console.log(2, '前端静态路由：', ele, ele.path, existRoute.includes(ele.path));

                    if (!existRoute.includes(ele.path)) {
                        pagePath[i.path].push({
                            label: ele.name + ele.path,
                            path: ele.path
                        })
                    }

                })
                // console.log('pagePath[i.path]', pagePath[i.path]);

            }
            if (!existRoute.includes(i.path)) {
                menuPath.push({
                    label: i.name + i.path,
                    path: i.path
                })
            }

        })
        // console.log(3, '菜单路由', menuPath);
        // console.log(4, '页面路由', pagePath);

        return {
            authKeys: Object.freeze([
                // { label: "菜单", value: 'menu' },
                // { label: "页面", value: 'page' },
                { label: "新增按钮", value: 'add' },
                { label: "删除按钮", value: 'del' },
                { label: "编辑按钮", value: 'edit' },
                { label: "查看按钮", value: 'view' },
                { label: "分配权限按钮", value: 'assignment' },
                { label: "绑定解绑按钮", value: 'bind' },
                { label: "批量操作按钮", value: 'batch' },
                { label: "修改密码按钮", value: 'editPassword' },
                { label: "启用按钮", value: 'enable' },
                { label: "禁用按钮", value: 'disable' },
                { label: "更新状态", value: 'updateStatus' },
                { label: "审核", value: 'audit' },
                { label: "分配角色", value: 'assignRole' },
            ]),
            iconFilter: '',
            elementIcons: elementIcons,
            formLabelAlign: {
                permissionName: null,
                permissionDesc: null,
                uri: null,
                code: null,
                path: null,
                title: null,
                icon: null,
                visible: 1,
                sort: null,
            },
            options: [],
            rules: {
                permissionName: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                path: [
                    { required: true, message: '请选择路径', trigger: 'blur' }
                ],
                icon: [
                    { required: true, message: '请选择图标', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入权限排序', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入权限标识', trigger: 'blur' }
                ],
                visible: [
                    { required: true }
                ],
            },
            menuPath: Object.freeze(menuPath),
            pagePath: Object.freeze(pagePath),
            buttonCodePrefix: null,
        }
    },
    created() {
        // 初始化 options 值
        this.initOptions();
    },
    computed: {
        filteredIcons() {
            return this.elementIcons.filter(icon =>
                icon.toLowerCase().includes(this.iconFilter.toLowerCase())
            );
        },
    },
    watch: {
        handleType: {
            handler(val, old) {
                // console.log(110, '权限type变化', val, old, this.type, this.menuPath);
                this.options = val == 0 ? this.menuPath : [];
            },
            immediate: true
        },
        type: {
            handler(val) {
                // console.log('type变化===', val, this.handleType);
                if (this.handleType == 1) {
                    this.options = this.pagePath[val];
                }
            },
            immediate: true
        }
    },
    methods: {
        initOptions() {
            // 根据 handleType 初始化 options
            if (this.handleType === 0) {
                this.options = this.menuPath;
            } else if (this.handleType === 1 && this.type) {
                this.options = this.pagePath[this.type] || [];
            } else {
                this.options = [];
            }
            // console.log('初始化 options:', this.options, 'handleType:', this.handleType, 'type:', this.type);
        },
        fillForm(data) {
            if (data.type == 2) {
                let t = data.code.split(':');
                this.buttonCodePrefix = t[0];
                data.code = t[1]
            }
            Object.keys(this.formLabelAlign).forEach(key => {
                if (data[key] && key === 'icon') {
                    this.formLabelAlign[key] = data[key].includes('el-icon') ? data[key] : 'el-icon-' + data[key];
                } else {
                    this.formLabelAlign[key] = data[key];
                }

            })
        },
        selectIcon(icon) {
            this.formLabelAlign.icon = icon;

        },
        close() {
            this.$emit('closeModal');
        },
        submit() {
            this.$refs.form.validate(res => {
                if (res) {
                    if (this.isEdit) {
                        this.formLabelAlign.code = this.buttonCodePrefix + ":" + this.formLabelAlign.code
                    }
                    this.$emit('submit', this.formLabelAlign)
                }
            })

        },
    }
}
</script>

<style scoped>
.icon-selector {
    padding: 10px;
}

.icon-list {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
    max-height: 300px;
    overflow-y: auto;
}

.icon-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40px;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s;
}

.icon-item:hover {
    background-color: #f5f7fa;
}

.icon-item.active {
    background-color: #ecf5ff;
    color: #409eff;
}

.icon-item i {
    font-size: 20px;
}
</style>